package com.example.eat.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.eat.database.RecipeDatabaseHelper;
import com.example.eat.model.User;

public class UserDao {
    private RecipeDatabaseHelper databaseHelper;

    public UserDao(Context context) {
        databaseHelper = new RecipeDatabaseHelper(context);
    }

    public long registerUser(User user) {
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(RecipeDatabaseHelper.COLUMN_USERNAME, user.getUsername());
        values.put(RecipeDatabaseHelper.COLUMN_PASSWORD, user.getPassword());

        long id = db.insert(RecipeDatabaseHelper.TABLE_USERS, null, values);
        db.close();
        return id;
    }

    public User loginUser(String username, String password) {
        User user = null;
        String selectQuery = "SELECT * FROM " + RecipeDatabaseHelper.TABLE_USERS +
                " WHERE " + RecipeDatabaseHelper.COLUMN_USERNAME + " = ?" +
                " AND " + RecipeDatabaseHelper.COLUMN_PASSWORD + " = ?";

        SQLiteDatabase db = databaseHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, new String[]{username, password});

        if (cursor.moveToFirst()) {
            user = new User();
            user.setId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_ID)));
            user.setUsername(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_USERNAME)));
            user.setPassword(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_PASSWORD)));
        }

        cursor.close();
        db.close();
        return user;
    }

    public boolean checkUsernameExists(String username) {
        boolean exists = false;
        String selectQuery = "SELECT * FROM " + RecipeDatabaseHelper.TABLE_USERS +
                " WHERE " + RecipeDatabaseHelper.COLUMN_USERNAME + " = ?";

        SQLiteDatabase db = databaseHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, new String[]{username});

        exists = cursor.moveToFirst();

        cursor.close();
        db.close();
        return exists;
    }
}